import { useRoutesStore } from '@/stores/router'
import router from './index'
import { TOKEN } from '@/config/constants'

const allowList = ['login', '404', '403']
const loginRoutePath = '/login'
const defaultRoutePath = '/dashboard'
router.beforeEach((to, from, next) => {
  const { asyncRoute, loadMenus } = useRoutesStore()
  const token = localStorage.getItem(TOKEN)
  if (token) {
    if (to.path === loginRoutePath) {
      next()
      // NProgress.done()
    } else {
      if (asyncRoute.routes.length === 0) {
        // 从服务端拉去权限列表
        loadMenus()
          .then(() => {
            // resetRouter();
            asyncRoute.routes.forEach((route) => {
              router.addRoute(route)
            })
            if (asyncRoute.routes.length === 0) {
              next({ path: defaultRoutePath })
            } else {
              if (to.path === '/') {
                next({ path: defaultRoutePath })
              }
              // 请求带有 redirect 重定向时，登录自动重定向到该地址
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                next({ ...to, replace: true })
              } else {
                next({ path: redirect })
              }
            }
          })
          .catch(() => {
            next({ path: loginRoutePath })
          })
      } else {
        next()
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
    }
  }
})
